﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using Pampa.CRUD.Configuration;
using Pampa.CRUD.Core;
using Pampa.MVC.Data;
using Pampa.MVC.Fluent.Crud.Groups;

namespace Pampa.MVC.Fluent.Crud.Items
{
    public class EntityAbstractItemBuilder<TGroup, TEditor, TEntity, TThis> : EditItemBuilder<TGroup, TEditor, TEntity, TThis> where TThis : EntityAbstractItemBuilder<TGroup, TEditor, TEntity, TThis>
    {
        private readonly EntityAbstractItem _item;
        private readonly string _parentGroupId;
        
        public EntityAbstractItemBuilder(EntityAbstractItem item, string parentGroupId) : base(item)
        {
            _item = item;
            _parentGroupId = parentGroupId;
        }

        public EntityAbstractItemBuilder(GroupBuilder<TGroup, TEditor> group, EntityAbstractItem item) : base(group, item)
        {
            _item = item;
        }

        public TThis Parent(Expression<Func<TGroup, object>> action, Expression<Func<TEntity, object>> action2)
        {
            _item.ParentId = GetId(action);
            _item.ForeingProperty = GetId(action2);

            return (TThis)this;
        }

        public TThis Id(Expression<Func<TEntity, object>> action)
        {
            _item.PropertyId = GetId(action);
            return (TThis)this;
        }

        public TThis Where(Expression<Func<TEntity, bool>> filter)
        {
            var groupId = (this.ParentGroup != null) ? this.ParentGroup.GetGroupId() : _parentGroupId;
            EntityManager.AddFilter(groupId + "_" + _item.Id, filter);
            return (TThis)this;
        }
    }
}
